package com.example.demo.com.example.singleton;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

//与懒汉式类似，只不过放入容器中统一管理
public class ContainerSingleton {

    //1私有化构造器
    private ContainerSingleton(){}

    //2创建注册式的单例容器
    private static Map<String ,Object> containerMap = new ConcurrentHashMap<String,Object>();

    public static Object getInstance(String className){
        synchronized (containerMap){
            if(!containerMap.containsKey(className)){
                Object obj = null;
                try {
                    obj = Class.forName(className).newInstance();
                    containerMap.put(className,obj);
                }catch (Exception e){
                    e.printStackTrace();
                }
                return obj;
            }else{
                return containerMap.get(className);
            }
        }
    }
}
